#include "ColorDiscrimination.h"
int red = 0;
int green = 0;
int blue = 0;
int redValue = 0;
int greenValue = 0;
int blueValue = 0;

void PinInit(){
  Serial.begin(115200); //串口的频率
  pinMode(s0,OUTPUT); //配置颜色传感(s0,s1,s2,s3)引脚模式为输出
  pinMode(s1,OUTPUT);
  pinMode(s2,OUTPUT);
  pinMode(s3,OUTPUT);
  pinMode(out,INPUT); //配置颜色传感out引脚模式为输入
  pinMode(RedLed,OUTPUT); //配置七彩灯的三个输入引脚模式为输出
  pinMode(GreenLed,OUTPUT);
  pinMode(BlueLed,OUTPUT);
  
  digitalWrite(s0,HIGH); //设置s0为HIGH,s1为LOW,比率因子为20%
  digitalWrite(s1,LOW);
  
  digitalWrite(RedLed,LOW);
  digitalWrite(GreenLed,LOW);
  digitalWrite(BlueLed,LOW);
}


void ColorFilter(){
   delay(1000);
  digitalWrite(s2,LOW);digitalWrite(s3,LOW);//L L 红色
  redValue = 255 -  pulseIn(out,LOW); //获取red的数值
  
  digitalWrite(s3,HIGH);//L H 蓝色
  blueValue = 255 -  pulseIn(out,LOW); //获取blue的数值
  
  digitalWrite(s2,HIGH);//H H 绿色
  greenValue = 255 - pulseIn(out,LOW); //获取green的数值

  green=greenValue/10; //由于捕获的数据脉冲不稳定，所以不用个位来比较
  red=redValue/10;
  blue=blueValue/10;
}

void color(){
 if(red==blue&&red==green)
      White(); //白灯
   else{
   if(redValue>blueValue&&redValue>greenValue){ 
      if((red==blue||red==(blue+1))&&greenValue<blueValue)
       Purple(); //紫灯
      else if(red==green||red==(green+1))
        Yellow(); //黄灯
      else
         Red(); //红灯   
   }
   else if(blueValue>redValue&&blueValue>greenValue){
     if(blue==green)
       Cyan(); //青灯
     else if((red==blue||red==(blue+1)))
       Purple(); //紫色
      else
       Blue(); //蓝色
   }  
   else if(greenValue>redValue&&greenValue>blueValue){
     if(blue==green)
       Cyan(); //青灯
     else if(red==green||red==(green+1))
        Yellow(); //黄灯
     else
      Green(); //绿灯
   } 
   else{
   }
   }

}

void ColorShow(){
  Serial.print("R:");
  Serial.print(redValue ,DEC);
  Serial.print(" G:");
  Serial.print(greenValue ,DEC);
  Serial.print(" B:");
  Serial.println(blueValue ,DEC);
}

void Red(){
  digitalWrite(RedLed,HIGH);
  digitalWrite(GreenLed,LOW);
  digitalWrite(BlueLed,LOW);
}

void Blue(){
  digitalWrite(RedLed,LOW);
  digitalWrite(GreenLed,LOW);
  digitalWrite(BlueLed,HIGH);
}

void Green(){
  digitalWrite(RedLed,LOW);
  digitalWrite(GreenLed,HIGH);
  digitalWrite(BlueLed,LOW);
}

void Yellow(){
  digitalWrite(RedLed,HIGH);
  digitalWrite(GreenLed,HIGH);
  digitalWrite(BlueLed,LOW); 
}

void Cyan(){
 digitalWrite(RedLed,LOW);
  digitalWrite(GreenLed,HIGH);
  digitalWrite(BlueLed,HIGH); 
}

void Purple(){
  digitalWrite(RedLed,HIGH);
  digitalWrite(GreenLed,LOW);
  digitalWrite(BlueLed,HIGH); 
}

void White(){
  digitalWrite(RedLed,HIGH);
  digitalWrite(GreenLed,HIGH);
  digitalWrite(BlueLed,HIGH);
}
